<template>
  <div class="register">
    <div class="content">
      <van-nav-bar
        title="注册"
        left-text="返回"
        left-arrow
        fixed
        @click-left="onClickLeft"
      />
      <div>
        <div class="idenfy">注册身份</div>
        <van-radio-group v-model="modelType" class="idenfyWrap">
          <van-radio v-show="isVolunteer" name="6" class="inlineRedio">
            志愿者
          </van-radio>
          <van-radio
            v-show="!isVolunteer && !isCode"
            name="5"
            class="inlineRedio"
            >学生</van-radio
          >
          <van-radio
            v-show="!isVolunteer && !isCode"
            name="3"
            class="inlineRedio"
            >咨询师</van-radio
          >
          <van-radio
            v-show="!isVolunteer && !isCode"
            name="4"
            class="inlineRedio"
            >家长</van-radio
          >
          <van-radio
            v-show="!isVolunteer && isCode"
            name="7"
            class="inlineRedio"
            >{{ isEnterprise ? '企业员工' : '学生' }}</van-radio
          >
        </van-radio-group>
      </div>
      <van-form class="login-form" @submit="onSubmit">
        <van-field
          v-if="modelType === '5'"
          v-model="loginForm.region"
          class="el-form-item"
          is-link
          readonly
          label="地区"
          placeholder="请选择所在地区"
          name="region"
          @click="regionShow = true"
        />

        <RegionSelect
          v-model="loginForm.region"
          v-model:visible="regionShow"
          v-model:regionIds="loginForm.regionIds"
        ></RegionSelect>

        <van-field
          v-if="modelType === '5'"
          :model-value="loginForm.bladeUserTenantInfos?.tenantName"
          class="el-form-item"
          is-link
          readonly
          label="学校"
          placeholder="请选择所在学校"
          @click="schoolShow = true"
        />

        <SchoolSelect
          v-model="loginForm.bladeUserTenantInfos"
          v-model:visible="schoolShow"
          :region-ids="loginForm.regionIds"
        ></SchoolSelect>

        <van-field
          v-if="modelType === '5'"
          :model-value="loginForm.level?.name"
          class="el-form-item"
          name="level"
          label="年级"
          placeholder="年级"
          :rules="[{ required: true, message: '请正确填写年级' }]"
          readonly
          is-link
          @click="classShow = true"
        />

        <ClassSelect v-model:visible="classShow" v-model="loginForm.level">
        </ClassSelect>

        <van-field
          v-if="modelType === '5'"
          v-model="loginForm.class"
          class="el-form-item"
          label="班级"
          placeholder="班级"
          name="classNo"
          :rules="[{ required: true, message: '请正确填写班级' }]"
        />

        <van-field
          v-model="loginForm.account"
          class="el-form-item"
          name="account"
          label="用户名"
          :placeholder="
            isVolunteer ? '请输入志愿者编号' : '英文字母、数字3-30位'
          "
          :rules="[
            { required: true, pattern: patAccount, message: '请正确填写账号' },
          ]"
        />
        <van-field
          v-if="modelType === '5'"
          v-model="loginForm.code"
          class="el-form-item"
          name="code"
          label="学号"
          placeholder="学号"
          :rules="[{ required: true, message: '请正确填写学号' }]"
        />
        <van-field
          v-model="loginForm.password"
          class="el-form-item"
          type="password"
          name="password"
          label="密码"
          placeholder="英文字母、数字4-8位"
          :rules="[
            { required: true, pattern: patPassWord, message: '请正确填写密码' },
          ]"
        />
        <van-field
          v-model="loginForm.password2"
          class="el-form-item"
          type="password"
          name="password2"
          label="确认密码"
          placeholder="英文字母、数字4-8位"
          :rules="[
            {
              required: true,
              pattern: patPassWord,
              message: '请正确填写确认密码',
            },
          ]"
        />
        <van-field
          v-if="isCode"
          v-model="loginForm.grade"
          class="el-form-item"
          is-link
          readonly
          :label="isEnterprise ? '岗位' : '年级'"
          name="grade"
          :placeholder="isEnterprise ? '请选择岗位' : '请选择年级'"
          :rules="[
            {
              required: true,
              message: isEnterprise ? '请选择岗位' : '请选择年级',
            },
          ]"
          @click="isShowPicker = true"
        />
        <van-popup v-model:show="isShowPicker" round position="bottom">
          <van-picker
            :columns="gradeList2"
            @cancel="isShowPicker = false"
            @confirm="confirm"
          />
        </van-popup>

        <van-field
          v-model="loginForm.realName"
          class="el-form-item"
          name="realName"
          label="真实姓名"
          placeholder="中文2-30位"
          :rules="[
            { required: true, pattern: patName, message: '请正确填写真实姓名' },
          ]"
        />
        <van-field
          v-model="state.value"
          class="el-form-item"
          readonly
          clickable
          label="性别"
          placeholder="选择性别"
          name="sex"
          @click="showPicker"
        />
        <van-popup v-model:show="state.showPicker" round position="bottom">
          <van-picker
            ref="picker"
            :columns="columns"
            :columns-field-names="customFieldName"
            @cancel="state.showPicker = false"
            @confirm="onConfirm"
          />
        </van-popup>
        <van-field
          v-model="loginForm.cardNo"
          class="el-form-item"
          name="cardNo"
          label="身份证号"
          placeholder="身份证号"
          :rules="[
            {
              validator: validatorCardNo,
              message: '请正确填写身份证号',
            },
          ]"
        />
        <van-field
          v-model="loginForm.phone"
          class="el-form-item"
          name="phone"
          label="手机号"
          placeholder="手机号"
          :rules="[
            { required: true, pattern: patPhone, message: '请正确填写手机号' },
          ]"
        />
        <van-cell-group class="msgBtn">
          <van-field
            v-model="loginForm.smsCode"
            class="el-form-item"
            name="smsCode"
            center
            clearable
            label="短信验证码"
            placeholder="请输入短信验证码"
          >
            <template #button>
              <van-button
                class="msg-text"
                size="small"
                type="primary"
                :class="[{ display: msgKey }]"
                @click="handleSend"
                >{{ msgText }}</van-button
              >
            </template>
          </van-field>
        </van-cell-group>

        <van-row class="regist">
          <van-col span="12" style="text-align: left">
            <van-radio
              v-model="readflg"
              name="read"
              class="inlineRedio"
            ></van-radio>
            <span @click="openieyi">《注册协议》</span>
          </van-col>
        </van-row>
        <van-button type="default" block native-type="submit" class="subbtn">
          立即注册
        </van-button>
      </van-form>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, watch, Ref, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Notify } from 'vant'
import { setToken, setUser } from '../../../util/auth'
import { loginByUsername } from '../../../api/login/login'
import { register, getMsgCode } from '../../../api/login/login'
import RegionSelect from '/@/components/RegionSelect.vue'
import SchoolSelect from '/@/components/SchoolSelect.vue'
import ClassSelect from '/@/components/ClassSelect.vue'
import { useVolunteer } from './volunteer'
import { useQrcode } from './qrcode'
import { useLoginAfter } from '../utils'
import { getList } from '/@/api/system/grade'
import { useStore } from '/@/store'

export default defineComponent({
  components: {
    RegionSelect,
    SchoolSelect,
    ClassSelect,
  },
  setup(props, context) {
    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    const picker = ref(null)
    const modelType = ref('')
    const showID = ref(false)
    const loginForm = reactive({
      tenantId: '',
      account: '',
      password: '',
      code: '',
      sex: '',
      school: {},
      grade: '',
    })
    const state = reactive({
      showPicker: false,
      value: '',
    })
    const customFieldName = {
      text: 'tenantName',
      values: 'tenantId',
    }
    const phoneState = {
      msgText: '发送验证码',
      msgKey: false,
      msgTime: 60,
    }
    const msgText = ref('发送验证码')
    const columns = reactive([])
    const readflg = ref('')
    const patAccount = /^[a-zA-Z0-9]{3,30}$/
    const patPassWord = /^[a-zA-Z0-9]{4,8}$/
    const patPhone = /^1\d{10}$/
    const parCarno = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
    const patName = /^[\u4e00-\u9fa5]{2,30}$/

    const regionShow = ref(false)
    const schoolShow = ref(false)
    const classShow = ref(false)
    const isShowPicker = ref(false)
    const isEnterprise = computed(() => {
      return store?.state?.enterprise.includes((route.query as any).tenantId)
    })

    const { isVolunteer } = useVolunteer({ modelType })
    const { loginRedirect } = useLoginAfter()
    const { isCode } = useQrcode({ modelType })
    const { gradeList, gradeList2 } = useGrade((route.query as any).tenantId)

    const onCancel = () => {
      isShowPicker.value = false
    }
    const confirm = (value: string, index: number) => {
      loginForm.grade = value
      isShowPicker.value = false
    }

    watch(
      () => loginForm.grade,
      (val) => {
        console.log(val)
      }
    )

    return {
      isEnterprise,
      isVolunteer,
      isCode,
      isShowPicker,
      gradeList,
      gradeList2,
      regionShow,
      schoolShow,
      classShow,
      patAccount,
      patPassWord,
      patPhone,
      parCarno,
      patName,
      modelType,
      showID,
      loginForm,
      readflg,
      state,
      columns,
      picker,
      customFieldName,
      phoneState,
      msgText,
      validatorCardNo(value: string) {
        if (!value) return true
        return parCarno.test(value)
      },
      handleSend() {
        if (!loginForm.phone) {
          Notify({ type: 'warning', message: '请输入正确的手机号' })
          return
        }
        if (phoneState.msgKey) return
        msgText.value = phoneState.msgTime + '秒后重发'
        phoneState.msgKey = true
        getMsgCode(loginForm.phone).then((res) => {})
        const time = setInterval(() => {
          phoneState.msgTime--
          msgText.value = phoneState.msgTime + '秒后重发'
          if (phoneState.msgTime == 0) {
            phoneState.msgTime = 60
            msgText.value = '发送验证码'
            phoneState.msgKey = false
            clearInterval(time)
          }
        }, 1000)
      },
      showPicker() {
        state.showPicker = true
        setTimeout(function () {
          const list = [
            {
              tenantName: '男',
              tenantId: 1,
            },
            {
              tenantName: '女',
              tenantId: '2',
            },
          ]
          picker.value.setColumnValues(0, list)
        }, 100)
      },
      onConfirm(item: any) {
        state.showPicker = false
        state.value = item.tenantName
        // state.value = item.tenantId
        loginForm.sex = item.tenantId
      },
      onClickLeft() {
        // history.back()
        router.push({ name: 'Login' })
      },
      openieyi() {
        if (!modelType.value) {
          Notify({
            type: 'warning',
            message: '请先选择注册身份',
          })
          return
        }
        router.push({
          name: 'Xieyi',
          query: {
            modelType: modelType.value,
          },
        })
      },
      onSubmit(values) {
        if (readflg.value != 'read') {
          Notify({
            type: 'warning',
            message: '请先阅读注册协议，并打钩!',
          })
          return
        }
        if (values.password2 != values.password) {
          Notify({
            type: 'warning',
            message: '两次输入密码不一致!',
          })
          return
        }
        if (modelType.value == '3') {
          values.tenantId = '760859'
          values.roleId = '1409899769264353281'
          values.deptId = '1408790545897656321'
          values.postId = '1409899893830987778'
          values.type = 'ZX'
        } else if (modelType.value == '4') {
          values.tenantId = '254563'
          values.roleId = '1409852686226436098'
          values.deptId = '1408790370395394050'
          values.postId = '1409898817463529474'
        } else if (modelType.value === '5') {
          values.tenantId = loginForm.bladeUserTenantInfos?.tenantId
          values.roleId = '-1'
          values.deptId = '-1'
          values.postId = '-1'
          values.gradeId = loginForm.level?.value
        } else if (modelType.value === '6') {
          values.tenantId = '302790'
          values.roleId = '-1'
          values.deptId = '-1'
          values.postId = '-1'
          values.gradeId = '-1'
          values.type = 'ZYZ'
        } else if (modelType.value === '7') {
          values.tenantId = route.query?.tenantId
          values.roleId = route.query?.roleId
          values.deptId = route.query?.deptId
          values.postId = route.query?.postId
          values.projectId = route.query?.projectId
          values.gradeId = gradeList.value.filter((item: any) => {
            return item.gradeName == values.grade
          })[0]?.gradeNo
          values.type = 'qrcode'
        }
        if (values.sex) {
          values.sex = values.sex === '男' ? 1 : 2
        }

        register(values).then((res) => {
          loginByUsername(values).then((res) => {
            const loginfo = res.data.data
            setToken(loginfo.accessToken)
            const user = {
              account: loginfo.account,
              tenantId: loginfo.tenantId,
              userId: loginfo.userId,
              userName: loginfo.userName,
            }
            setUser(JSON.stringify(user))
            localStorage.setItem('fock_user_data', JSON.stringify(loginfo))
            loginRedirect()
            // router.push({
            //   name: 'Home',
            // })
          })
        })
      },
      onCancel,
      confirm,
    }
  },
  watch: {
    modelType: function (val) {
      this.showID = ['1', '2'].indexOf(val) > -1
    },
  },
})

function useGrade(tenantId: string) {
  let gradeList: Ref<any[]> = ref([])
  let gradeList2: Ref<any[]> = ref([])
  getList(tenantId || '111').then((res) => {
    gradeList.value = res.data.data
    gradeList2.value = res.data.data.map((item: any) => {
      return item.gradeName
    })
  })

  return {
    gradeList,
    gradeList2,
  }
}
</script>

<style lang="less" scoped>
.register {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  height: 100vh;
  overflow-y: auto;
  background: url('../imgs/bac.png') no-repeat center/cover;
}
.content {
  box-sizing: border-box;
  min-height: calc(100vh - 56px);
  padding: 45px 15px 15px 15px;
}
.idenfy {
  font-size: 13px;
  color: #3071b9;
  margin-top: 20px;
  margin-bottom: 20px;
}
.idenfyWrap {
  display: flex;
  margin-bottom: 20px;
}

.login-form {
}

.login-form .el-form-item {
  margin-bottom: 12px;
  opacity: 0.8;
  border-radius: 5px;
}
.login-form .msgBtn {
  opacity: 0.8;
  border-radius: 5px;
}
.regist {
  font-size: 14px;
  color: #3071b9;
  margin-top: 20px;
}

.subbtn {
  opacity: 0.8;
  margin-top: 30px;
  border-radius: 5px;
}

.inlineRedio {
  font-size: 14px;
  float: left;
  margin-left: 10px;
}
.msg-text.display {
  color: #ccc;
}
/deep/ .van-radio__label {
  color: #3071b9;
}
</style>
